package com.ywu.dev.admin.standard.service;

import com.ywu.boot.exception.YwuRuntimeException;
import com.ywu.common.utils.TimerIdGenerateUtil;
import com.ywu.dev.admin.spi.entity.YwuDevOpsCpuInfoEntity;
import com.ywu.dev.admin.spi.entity.YwuDevOpsMemoryInfoEntity;
import com.ywu.dev.admin.spi.entity.YwuDevOpsThreadInfoEntity;
import com.ywu.dev.admin.standard.config.YwuDevOpsConfig;
import com.ywu.dev.admin.standard.data.YwuDevOpsCpuInfoRepository;
import com.ywu.dev.admin.standard.data.YwuDevOpsMemoryInfoRepository;
import com.ywu.dev.admin.standard.data.YwuDevOpsThreadInfoRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName YwuDevOpsRecordService
 * @Description 记录上报的采样信息
 * @Author GroundDemo
 * @Date 2025/3/25 12:24
 * @Version 1.0
 **/
@Service
@Slf4j
public class YwuDevOpsRecordService {
    @Autowired
    private YwuDevOpsConfig config;

    @Autowired
    private YwuDevOpsCpuInfoRepository ywuDevOpsCpuInfoRepository;

    @Autowired
    private YwuDevOpsThreadInfoRepository ywuDevOpsThreadInfoRepository;

    @Autowired
    private YwuDevOpsMemoryInfoRepository ywuDevOpsMemoryInfoRepository;

    private static final List<YwuDevOpsCpuInfoEntity> cpuInfoEntityList = new ArrayList<>();

    private static final List<YwuDevOpsMemoryInfoEntity> memoryInfoEntityList = new ArrayList<>();

    private static final List<YwuDevOpsThreadInfoEntity> threadInfoEntityList = new ArrayList<>();

    private static final ReentrantLock cpuInfoLock = new ReentrantLock();

    private static final ReentrantLock memoryInfoLock = new ReentrantLock();

    private static final ReentrantLock threadInfoLock = new ReentrantLock();

    /**
    * @Author GroundDemo
    * @Description 记录CPU采样信息
    * @Date 12:29 2025/3/25
    * @Param [entityList]
    * @return void
    **/
    public void recordCpuInfo(List<YwuDevOpsCpuInfoEntity> entityList) {
        if (CollectionUtils.isEmpty(entityList)) {
            return;
        }
        cpuInfoLock.lock();
        try {
            // 先将当前列表添加到全局列表中
            cpuInfoEntityList.addAll(entityList);
            // 判断当前列表数量是否已经超过了阈值
            if (cpuInfoEntityList.size() > config.getMaxMapCacheSize()) {
                // 执行插入操作
                doCpuInsert();
            }
        } catch (Exception e) {
            log.error("record cpu info error {}", e.getMessage());
            throw new YwuRuntimeException("record cpu info error");
        } finally {
            cpuInfoLock.unlock();
        }
    }

    /**
    * @Author GroundDemo
    * @Description CPU采样信息入库
    * @Date 12:34 2025/3/25
    * @Param []
    * @return void
    **/
    private void doCpuInsert() {
        cpuInfoEntityList.forEach(res -> {
            res.setId(TimerIdGenerateUtil.nextId());
            res.createInfo("devAdmin");
        });
        ywuDevOpsCpuInfoRepository.inertBatchCpuInfo(cpuInfoEntityList);
        // 重置集合
        cpuInfoEntityList.clear();
    }

    /**
    * @Author GroundDemo
    * @Description 记录内存采样信息
    * @Date 12:37 2025/3/25
    * @Param [entityList]
    * @return void
    **/
    public void recordMemoryInfo(List<YwuDevOpsMemoryInfoEntity> entityList) {
        if (CollectionUtils.isEmpty(entityList)) {
            return;
        }
        memoryInfoLock.lock();
        try {
            // 先将当前列表添加到全局列表中
            memoryInfoEntityList.addAll(entityList);
            // 判断当前列表数量是否已经超过了阈值
            if (memoryInfoEntityList.size() > config.getMaxMapCacheSize()) {
                // 执行插入操作
                doMemoryInsert();
            }
        } catch (Exception e) {
            log.error("record memory info error {}", e.getMessage());
            throw new YwuRuntimeException("record memory info error");
        } finally {
            memoryInfoLock.unlock();
        }
    }

    /**
    * @Author GroundDemo
    * @Description 内存采样信息入库
    * @Date 12:38 2025/3/25
    * @Param []
    * @return void
    **/
    private void doMemoryInsert() {
        memoryInfoEntityList.forEach(res -> {
            res.setId(TimerIdGenerateUtil.nextId());
            res.createInfo("devAdmin");
        });
        ywuDevOpsMemoryInfoRepository.inertBatchMemoryInfo(memoryInfoEntityList);
        // 重置集合
        memoryInfoEntityList.clear();
    }

    /**
     * @Author GroundDemo
     * @Description 记录内存采样信息
     * @Date 12:37 2025/3/25
     * @Param [entityList]
     * @return void
     **/
    public void recordThreadInfo(List<YwuDevOpsThreadInfoEntity> entityList) {
        if (CollectionUtils.isEmpty(entityList)) {
            return;
        }
        threadInfoLock.lock();
        try {
            // 先将当前列表添加到全局列表中
            threadInfoEntityList.addAll(entityList);
            // 判断当前列表数量是否已经超过了阈值
            if (threadInfoEntityList.size() > config.getMaxMapCacheSize()) {
                // 执行插入操作
                doThreadInsert();
            }
        } catch (Exception e) {
            log.error("record thread info error {}", e.getMessage());
            throw new YwuRuntimeException("record thread info error");
        } finally {
            threadInfoLock.unlock();
        }
    }

    /**
     * @Author GroundDemo
     * @Description 内存采样信息入库
     * @Date 12:38 2025/3/25
     * @Param []
     * @return void
     **/
    private void doThreadInsert() {
        threadInfoEntityList.forEach(res -> {
            res.setId(TimerIdGenerateUtil.nextId());
            res.createInfo("devAdmin");
        });
        ywuDevOpsThreadInfoRepository.inertBatchThreadInfo(threadInfoEntityList);
        // 重置集合
        threadInfoEntityList.clear();
    }
}
